﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DllDependenciesAnalysis.AnalysisPlans
{
    public class AnalysisPlanManager
    {
        public static AnalysisPlanManager Instance { get; } = new AnalysisPlanManager();

        List<IAnalysisPlan> AnalysisPlans = new List<IAnalysisPlan>();

        private AnalysisPlanManager()
        {
            var allTypes = Assembly.GetExecutingAssembly().GetTypes();

            foreach (var type in allTypes)
            {
                if (type.IsAbstract || type.IsInterface)
                    continue;

                if (typeof(IAnalysisPlan).IsAssignableFrom(type) != true)
                    continue;

                var plan = (IAnalysisPlan)Activator.CreateInstance(type);
                AnalysisPlans.Add(plan);
            }
        }

        public List<IAnalysisPlan> GetAllAnalysisPlans() 
        {
            return AnalysisPlans;
        }

        public IAnalysisPlan GetAnalysisPlan(string planName)
        {
            var searchName = new[]
            {
                planName,
                $"{planName}Plan",
            };

            foreach (var name in searchName)
            {
                var plan = AnalysisPlans.FirstOrDefault(n => string.Equals(n.Name, name, StringComparison.OrdinalIgnoreCase));
                if (plan != null)
                    return plan;
            }

            return null;
        }
    }
}
